(function($) {
  function createWebSocket() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    var guid =
      S4() +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      S4() +
      S4();
    return new WebSocket("ws://192.168.21.159:8255/webSocket/server/" + guid);
  }

  function createBarChart(id, height) {
    var chart = new G2.Chart({
      container: id,
      forceFit: true,
      height: height
      // padding: [20, 20, 50, 30]
    });
    chart.scale("actualAmount", {
      // type: 'linear',
      alias: "金额(元)"
    });
    // chart.axis("city", {
    //   label: {
    //     textStyle: {
    //       fill: "#aaaaaa"
    //     }
    //   },
    //   tickLine: {
    //     alignWithLabel: false,
    //     length: 0
    //   }
    // });

    // chart.axis("actualAmount", {
    //   label: {
    //     textStyle: {
    //       fill: "#aaaaaa"
    //     }
    //   }
    // });

    // chart.tooltip({
    //   share: true
    // });

    // chart.legend(false);
    chart.interval().position("top10Name*actualAmount");
    return chart;
  }

  function createLineChart(id, height) {
    var chart = new G2.Chart({
      container: id,
      forceFit: true,
      height: height,
      // padding: [ 20, 20, 20, 20 ],
      // background: {
      //   fill: '#0a1631',
      //   // opacity: 1,
      //   // fillOpacity: 1
      // },
      animate: false
    });

    // chart.scale("Data", {
    //   range: [0, 1],
    //   tickCount: 10,
    //   type: "linear"
    // });
    // chart.axis("Data", {
    //   label: {
    //     textStyle: {
    //       fill: "#aaaaaa"
    //     }
    //   }
    // });
    // chart.axis("sales", {
    //   label: {
    //     textStyle: {
    //       fill: "#aaaaaa"
    //     },
    //     formatter: text => {
    //       return text.replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
    //     }
    //   }
    // });
    // chart.tooltip({
    //   crosshairs: "y",
    //   share: true
    // });
    // chart.legend({
    //   attachLast: true
    // });
    // chart.scale({
    //   type: 'time'
    // })

    chart.axis("actualAmount", {
      title: {} // 展示 xField 对应坐标轴的标题
    });
    chart.line().position("dateTime*actualAmount");
    chart.area().position("dateTime*actualAmount");
    return chart;
  }

  function createLiqidChart(id, height, value, max) {
    var liquidPlot = new G2Plot.Liquid(document.getElementById(id), {
      title: {
        visible: true,
        text: "水波图"
      },
      statistic: "percent",
      width: height,
      height: height,
      min: 0,
      max: max || 100000,
      value: value,
      showValue: true
    });
    liquidPlot.render();
    return liquidPlot;
  }

  function createMap(id, height, dv) {
    var chart = new G2.Chart({
      container: id,
      forceFit: true,
      width: 500,
      height: 600,
      animate: false
    });
    chart.scale({
      latitude: { sync: true, nice: false },
      longitude: { sync: true, nice: false }
    });
    // chart.legend(false);
    // chart.axis(false);
    // chart.tooltip(false);

    chart.tooltip({
      showTitle: false,
      itemTpl: "<span>{name}: {value}</span>"
    });

    chart.legend(false);
    chart.axis(false);
    // chart.tooltip(false);

    var cdv = chart.view();
    cdv.source(dv);
    cdv
      .polygon()
      .position("longitude*latitude")
      .tooltip("name*value", (name, value) => ({ name, value }))
      .color("value", value => {
        console.log(value);
        if (value < 100000) {
          return "#27AE60";
        } else if (value < 300000) {
          return "#1ABC9C";
        } else if (value < 800000) {
          return "#2980B9";
        }else if (value < 1200000) {
          return "#E67E22";
        } else {
          return "#C0392B";
        }
      })
      .label("name", {
        offset: 0,
        textStyle: {
          fontSize: 10,
          fill: "#fff"
        }
      })
      .style({
        fill: "#DDDDDD",
        stroke: "#b1b1b1",
        lineWidth: 0.5,
        fillOpacity: 0.85
      });

    // const userView = chart.view();
    // userView.source(userData);
    // userView.heatmap()
    //   .position('longitude*latitude')
    //   .color('value', '#F51D27-#FA541C-#FF8C12-#FFC838-#FAFFA8-#80FF73-#12CCCC-#1890FF-#6E32C2')
    //   .size(500 / 20)
    //   .style({
    //     blur: 500 / 15
    //   });
    return chart;
  }

  $(function() {
    var $H = $(window).height() - 60;
    var $BAR = createBarChart("barChart", 400);
    var $LINE = createLineChart("lineChart", 400);
    var $QIU = null
    var $DV = null;
    var $MAP = null;
    var $LIQUID = null;
    var ws = null;
    var first = false;
    var lineData = [];
    var timer = 0;
    var dxmbz = 20000000
    var cd = 0

    var qOpt = {
      type: 'liquidFill',
        radius: '50%',
        data: [0],
        color: 'rgba(67,209,100,1)',
        label: {
            normal: {
                color: '#fff',
                insideColor: 'transparent',
                textStyle: {
                    fontSize: 12,
                    fontWeight: 'bold',
                    fontFamily: 'Microsoft YaHei'
                }
            }
        },
        outline: {
            show: true,
            borderDistance: 5,
            itemStyle: {
                borderColor: 'rgba(67,209,100,1)',
                borderWidth: 2
            }
        },
        backgroundStyle: {
            color: 'rgba(67,209,100,.3)'
        }
    }
   

    function search(params) {
      var json = JSON.stringify(params);
      if (ws) {
        ws.send(json);
      } else {
        ws = createWebSocket();
        ws.onclose = function() {
          alert("ws close!!");
        };
        ws.onopen = function() {
          $("#loader").show();
          lineData.push({ dateTime: new Date(), actualAmount: 0 });
          ws.send(json);

          window.setInterval(function() {
            ws.send('{"msg": "ping"}');
          }, 10000);
        };

        ws.onmessage = function(e) {
          if (e.data === "pong") {
            return;
          }
          var data;
          try {
            data = JSON.parse(e.data);
          } catch (error) {
            return;
          }
          var barData = data.top10;
          var mapData = data.provinceMap;
          cd = data.countData.actualAmount;
          lineData.push(data.data);
          if (!first) {
            $BAR.source(barData);
            $BAR.render();
            $LINE.source(lineData, {
              dateTime: {
                alias: "时间",
                type: "time",
                mask: "mm:ss",
                nice: false
              },
              actualAmount: {
                alias: "金额",
                min: 0
              },
              type: {
                type: "cat"
              }
            });
            $LINE.render();
            $("#loader").hide();
            $("#total").text(data.countData.actualAmount).parent().show()
            $('#qiuTit').show()
          } else {
            $("#total").text(data.countData.actualAmount)
            $BAR.changeData(barData);
            if (lineData.length > 50) {
              lineData.shift();
              console.log(lineData)
            }
            $LINE.changeData(lineData);
          }

          if (window.$LV === "4") {

            function fn() {
              $DV.rows = $DV.rows.map(function(r) {
                mapData.forEach(function(p) {
                  if (p.province === r.name) {
                    r.value = p.actualAmount;
                  }
                });
                return r;
              });
              $MAP.view().source($DV);
              $MAP.render();
  
              $("#liquidChart").empty();
              qOpt.data[0] = data.countData.actualAmount / dxmbz
              $QIU.setOption({series:[qOpt]})
            }

            if(!first) {
              fn()
            } else {
              if(timer === 0) {
                timer = setTimeout(function(){
                  fn()
                  timer = 0
                },5000)
              }
            }

            // $DV.rows = $DV.rows.map(function(r) {
            //   mapData.forEach(function(p) {
            //     if (p.province === r.name) {
            //       r.value = p.actualAmount;
            //     }
            //   });
            //   return r;
            // });
            // $MAP.view().source($DV);
            // $MAP.render();

            // $("#liquidChart").empty();
            
            // qOpt.data[0] = data.countData.actualAmount / dxmbz
            // $QIU.setOption({series:[qOpt]})
          }

          
          first = true;
        };
      }
    }
    $("select").niceSelect();

    $("#search").on("click", function(e) {
      var lv = window.$LV;
      var org = $("#org").val();
      var query = "";
      var date = new Date().toLocaleDateString();
      var params = {
        reportLv: lv,
        orgId: org,
        orderDate: date,
      }
      if (lv === "4") {
        query = "org";
      } else if (lv === "5") {
        query = params.queryParam = params.province = $("#province").val();
      } else if (lv === "6") {
        query = params.queryParam = params.city = $("#city").val();
        params.province = $("#province").val()
      } else if (lv === "7") {
        query = params.queryParam  = $("#jxs").val();
      }

      if (org && query) {
        search(params);
      }
    });

    if (window.$LV === "6") {
      var $city = $("#city");
      var $province = $("#province");
      $province.on("change", function(e) {
        var cn = $province.val();
        $city.empty().append('<option value="">请选择市区</option>');
        $($cityList).each(function(i, el) {
          if (el.name === cn) {
            $(el.cc).each(function(i, c) {
              $city.append(
                '<option value="' + c.name + '">' + c.name + "</option>"
              );
            });
          }
        });
        $city.niceSelect("update");
      });
    }

    if(window.$LV === '4') {
      $.get("./js/data/china.full.geo.json").then(function(json) {
        $DV = new DataSet.View()
          .source(json, {
            type: "GeoJSON"
          })
          .transform({
            type: "map",
            callback(row) {
              row.value = 0;
              return row;
            }
          });
        $MAP = createMap("mapChart", $H * 0.7, $DV);
      });

      $QIU = echarts.init(document.getElementById('qiu'))
      // $QIU.setOption({series:[qOpt]})

      $('#mbz').on('blur', function() {
        var val = window.parseFloat($('#mbz').val())
        if(val) {
          dxmbz = val
          qOpt.data[0] = cd / dxmbz
          $QIU.setOption({series:[qOpt]})
        }
      })
    }
  });
})(jQuery);
